package com.isunland.managesystem.ui;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.TextView;
import com.isunland.managesystem.R;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.DefaultAsyncHttpClient;
import com.isunland.managesystem.common.MyApplication;
import com.isunland.managesystem.entity.VersionUpdate;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import java.io.File;
import java.text.DecimalFormat;
import org.apache.http.Header;

//import android.app.AlertDialog.Builder;
//import android.content.DialogInterface;
//import android.content.DialogInterface.OnClickListener;
//import android.content.Intent;

//import java.security.PrivateKey;

@SuppressWarnings("deprecation") public class UpdateDialogFragment extends DialogFragment {

  //private static final String EXTRA_HINT_ID = "com.isunland.managesystem.ui.EXTRA_HINT_ID";
  //private static final String EXTRA_HINT_STRING = "com.isunland.managesystem.ui.EXTRA_STRING";
  private static final String EXTRA_VERSION_UPDATE =
      "com.isunland.managesystem.ui.EXTRA_VERSION_UPDATE";
  private static final int notificationID = 1;
  @SuppressLint("StaticFieldLeak") private static UpdateDialogFragment mFragment;
  private static boolean isDownloading;
  private AlertDialog mDialog;
  private VersionUpdate mVersion;
  //private String filePath = "";
  private NotificationManager mNotificationManager;
  private Notification mNotification;
  private File mAPKFile;
  private RemoteViews mRemoteViews;
  private Context mAppContext = MyApplication.getAppContext();

  /**
   * @param update 更新信息
   */
  public static UpdateDialogFragment newInstance(VersionUpdate update) {
    Bundle argsBundle = new Bundle();
    argsBundle.putSerializable(EXTRA_VERSION_UPDATE, update);

    if (mFragment == null) {

      mFragment = new UpdateDialogFragment();
    }
    if (mFragment.isAdded() || isDownloading) {
      return null;
    }
    mFragment.setArguments(argsBundle);
    //Activity mActivity = mFragment.getActivity();
    return mFragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    mVersion = (VersionUpdate) getArguments().getSerializable(EXTRA_VERSION_UPDATE);
    //mHintString = getArguments().getString(EXTRA_HINT_STRING);
    super.onCreate(savedInstanceState);
  }

  @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) {

    View v = getActivity().getLayoutInflater().inflate(R.layout.umeng_update_dialog, null);
    TextView mContentTv = (TextView) v.findViewById(R.id.umeng_update_content);
    mContentTv.setText(mVersion.getWhatsNew());
    TextView mVersionTv = (TextView) v.findViewById(R.id.umeng_update_version);
    String versionName = getResources().getString(R.string.updateHint, mVersion.getApkName());
    mVersionTv.setText(versionName);
    Button mOkBtn = (Button) v.findViewById(R.id.umeng_update_id_ok);
    Button mCancelBtn = (Button) v.findViewById(R.id.umeng_update_id_cancel);
    mOkBtn.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        downloadAPK();
        //if (getTargetFragment() != null) {
        //
        //    getTargetFragment().onActivityResult(
        //            getTargetRequestCode(),
        //            Activity.RESULT_OK, null);
        //
        //}
        mDialog.dismiss();
      }
    });

    mCancelBtn.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        mDialog.dismiss();
      }
    });

    mDialog = new AlertDialog.Builder(getActivity()).setView(v).create();

    return mDialog;
  }

  private void downloadAPK() {

    RequestParams params2 = new RequestParams("id", mVersion.getId());

    mAPKFile = new File(FileUtil.getFileDir(), mVersion.getApkName() + ".apk");

    File parentFile = mAPKFile.getParentFile();
    //不存在目录
    if (!parentFile.exists()) {
      //创建目录
      if (!parentFile.mkdirs()) {
        //创建目录失败，结束运行
        ToastUtil.show(R.string.create_file_failed);
        return;
      }
    }

    DefaultAsyncHttpClient.post(ApiConst.URL_DOWNLOAD_APK, params2,
        new FileAsyncHttpResponseHandler(mAPKFile) {

          long mProgressTime;

          @Override public void onStart() {
            ToastUtil.show(R.string.isDownLoading);
            //Toast.makeText(getActivity(), , Toast.LENGTH_SHORT).show();
            //				boolean checkReadPermission=mActivity.checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
            //				if(!checkReadPermission){
            //					return;
            //				}
            initNotifycation();
          }

          @Override public void onProgress(long bytesWritten, long totalSize) {
            if ((System.currentTimeMillis() - mProgressTime) > 2000) {
              isDownloading = true;
              mProgressTime = System.currentTimeMillis();
              notifyProgress(bytesWritten, mVersion.getTotalByte());
            }
          }

          @Override public void onSuccess(int statusCode, Header[] headers, File response) {
            isDownloading = false;
            Intent intent = getInstallIntent(mAPKFile);
            notifyInstallAPK(intent);
            //if (isAdded()) {
            // 用户离开当前界面,fragment在detach状态下.startActivity()会报错.
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            mAppContext.startActivity(intent);
            //}

          }

          @Override public void onFailure(int arg0, Header[] arg1, Throwable arg2, File arg3) {
            isDownloading = false;
            MyUtils.dismissDialog();
            ToastUtil.show(R.string.download_failed);
            //Toast.makeText(getActivity(), R.string.download_failed, Toast.LENGTH_SHORT).show();
            LogUtil.i("responseError=" + arg0 + arg2 + arg3);
          }
        });
  }

  private void initNotifycation() {
    mNotificationManager =
        (NotificationManager) mAppContext.getSystemService(Context.NOTIFICATION_SERVICE);
    mNotification = new Notification();
    mNotification.icon = R.drawable.ic_launcher;// 设置通知消息的图标
    mNotification.tickerText = "正在下载。。。";// 设置通知消息的标题
    mNotification.contentIntent = PendingIntent.getActivity(mAppContext, 0,
        new Intent(mAppContext, GuideMenuNewActivity.class), 0);
  }

  private void notifyProgress(long bytesWritten, long totalSize) {
    //如果服务端不返回文件大小,默认是6m.
    if (totalSize <= 0) {
      totalSize = 15 * 1024 * 1024;
    }

    int progressPercentage = (int) ((bytesWritten * 100 / totalSize));

    DecimalFormat format = new DecimalFormat("0.00");
    String progress = format.format(progressPercentage);
    if (mRemoteViews == null) {

      mRemoteViews = new RemoteViews(mAppContext.getPackageName(), R.layout.down_notification);
    }
    mRemoteViews.setImageViewResource(R.id.IconIV, R.drawable.ic_launcher);
    mRemoteViews.setTextViewText(R.id.tv_title_remoteView,
        mAppContext.getString(R.string.app_name));
    mRemoteViews.setTextViewText(R.id.progressTv, "已下载" + progress + "%");
    mRemoteViews.setProgressBar(R.id.progressBar, 100, progressPercentage, false);
    mNotification.contentView = mRemoteViews;
    mNotificationManager.notify(notificationID, mNotification);
  }

  private Intent getInstallIntent(File response) {
    Intent intent = new Intent(Intent.ACTION_VIEW);

    intent.setDataAndType(Uri.fromFile(response), "application/vnd.android.package-archive");
    return intent;
  }

  private void notifyInstallAPK(Intent intent) {

    RemoteViews remoteViews =
        new RemoteViews(mAppContext.getPackageName(), R.layout.down_notification);
    remoteViews.setImageViewResource(R.id.IconIV, R.drawable.ic_launcher);
    if (mRemoteViews == null) {
      mRemoteViews = new RemoteViews(mAppContext.getPackageName(), R.layout.down_notification);
    }
    mRemoteViews.setTextViewText(R.id.tv_title_remoteView,
        mAppContext.getString(R.string.app_name));
    remoteViews.setTextViewText(R.id.progressTv, "下载完成");
    remoteViews.setProgressBar(R.id.progressBar, 100, 100, false);
    mNotification.contentView = remoteViews;
    if (intent != null) {
      mNotification.contentIntent = PendingIntent.getActivity(mAppContext, 0, intent, 0);
    }
    mNotification.flags = Notification.FLAG_AUTO_CANCEL;
    mNotificationManager.notify(notificationID, mNotification);
    // notificationManager.cancel(notificationID);
  }
}
